package org.example.spring_frist.LibraryProject.config;

import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "org.example.spring_frist.LibraryProject.mapper",
        sqlSessionFactoryRef = "librarySqlSessionFactory")
public class libraryConfig {
    @Bean(name = "libraryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.library")
    //上面会加载配置文件，如果路径不对报Failed to configure a DataSource:
    public DataSource libraryDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "librarySqlSessionFactory")
    public SqlSessionFactory librarySqlSessionFactory(
            @Qualifier("libraryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:MapperXml/library/**.xml"));

        return bean.getObject();
    }

    @Bean(name = "librarySqlSessionTemplate")
    public SqlSessionTemplate librarySqlSessionTemplate(
            @Qualifier("librarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "libraryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager(
            @Qualifier("libraryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
